package com.code.qgjx.controller.dealcontroller;

import com.alibaba.fastjson.JSON;
import com.code.qgjx.entity.ResignCommit;
import com.code.qgjx.entity.StudentJob;
import com.code.qgjx.entity.User;
import com.code.qgjx.service.ResignCommitService;
import com.code.qgjx.service.StudentJobService;
import com.code.qgjx.service.UserService;
import com.code.qgjx.tools.Layui;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/Sys")
@Api("辞职申请管理相关api")
@Slf4j
public class ResignController {

    @Autowired
    private ResignCommitService resignCommitService;

    @Autowired
    private UserService userService;

    @Autowired
    private StudentJobService studentJobService;

    /**
     * 获取辞职申请列表
     *
     * @param limit 每页记录数
     * @param page 页码
     * @param userId 用户ID（可选）
     * @param status 状态（可选）
     * @return 返回包含辞职申请列表和总数的JSON字符串
     */
    @RequestMapping("/getResignList")
    @ResponseBody
    public String getResignList(@RequestParam("limit") String limit, @RequestParam("page") String page,
                               @RequestParam(value = "userId", required = false) String userId  ,
                               @RequestParam(value = "status", required = false) String status) {
        // 将字符串参数转换为相应类型
        int lim = Integer.parseInt(limit);
        int start = (Integer.parseInt(page) - 1) * lim;
        Long userIds = null;
        if (userId != null) {
            userIds = Long.parseLong(userId);
        }
        Integer sta = null;
        if (status != null) {
            sta = Integer.parseInt(status);
        }
        // 调用服务获取辞职申请列表和总数
        List<Map> resignCommits = resignCommitService.getResignCommitsByUserId(userIds,sta, start, lim);
        int total = resignCommitService.getResignCommitCountByUserId(userIds);
        // 返回格式化的JSON字符串
        return JSON.toJSONString(Layui.data(total, resignCommits));
    }

    /**
     * 获取教师相关的辞职申请列表
     *
     * @param limit 每页记录数
     * @param page 页码
     * @param teacherId 教师ID
     * @return 返回包含辞职申请列表和总数的JSON字符串
     */
    @RequestMapping("/getTeacherResignList")
    @ResponseBody
    public String getTeacherResignList(@RequestParam("limit") String limit, @RequestParam("page") String page,
                                      @RequestParam("teacherId") String teacherId) {
        // 将字符串参数转换为相应类型
        int lim = Integer.parseInt(limit);
        int start = (Integer.parseInt(page) - 1) * lim;
        // 调用服务获取辞职申请列表和总数
        List<ResignCommit> resignCommits = resignCommitService.getResignCommitsByTeacherId(Long.parseLong(teacherId), start, lim);
        int total = resignCommitService.getResignCommitCountByTeacherId(Long.parseLong(teacherId));
        // 返回格式化的JSON字符串
        return JSON.toJSONString(Layui.data(total, resignCommits));
    }

    /**
     * 获取单个辞职申请详情
     *
     * @param id 辞职申请ID
     * @return 返回包含辞职申请详情的Map
     */
    @GetMapping("/getResign/{id}")
    @ResponseBody
    public Map<String, Object> getResign(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        ResignCommit resignCommit = resignCommitService.getResignCommit(id);
        // 查询学生信息
        if (resignCommit != null) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", resignCommit.getId());
            map.put("status", resignCommit.getStatus());
            map.put("remark", resignCommit.getRemark());
            User user = userService.getUserById(resignCommit.getUserId());
            map.put("name", user.getName());
            map.put("phone", user.getPhoto());
            map.put("timeSlot", user.getTimeSlot());
            result.put("code", 0);
            result.put("data", map);
        } else {
            result.put("code", 1);
            result.put("msg", "未找到对应的辞职申请记录");
        }
        return result;
    }

    /**
     * 添加辞职申请
     *
     * @param map 包含辞职申请信息的Map
     * @return 返回操作结果字符串
     */
    @RequestMapping("/addResign")
    @ResponseBody
    public String addResign(@RequestBody Map<String,Object> map) {
        ResignCommit resignCommit = new ResignCommit();
        resignCommit.setUserId(Long.parseLong(map.get("userId").toString()));
        resignCommit.setJobPositionId(Long.parseLong(map.get("jobPositionId").toString()));
        resignCommit.setTeacherId(Long.parseLong(map.get("teacherId").toString()));
        resignCommit.setStatus(0);
        try {
            resignCommit.setStatus(0); // 设置初始状态为待审批
            return resignCommitService.createResignCommit(resignCommit) ? "success" : "failure";
        } catch (Exception e) {
            return "failure";
        }
    }

    /**
     * 更新辞职申请
     *
     * @param resignCommit 更新后的辞职申请对象
     * @return 返回操作结果字符串
     */
    @RequestMapping("/updateResign")
    @ResponseBody
    public String updateResign(@RequestBody ResignCommit resignCommit) {
        try {
            // 获取原有申请
            ResignCommit original = resignCommitService.getResignCommit(resignCommit.getId());
            if (original == null) {
                return "not_found";
            }
            // 只允许修改未审批的申请
            if (original.getStatus() != 0) {
                return "approved";
            }
            return resignCommitService.updateResignCommit(resignCommit) ? "success" : "failure";
        } catch (Exception e) {
            return "failure";
        }
    }

    /**
     * 删除辞职申请
     *
     * @param id 辞职申请ID
     * @return 返回操作结果字符串
     */
    @RequestMapping("/deleteResign")
    @ResponseBody
    public String deleteResign(@RequestParam("id") Long id) {
        try {
            // 获取原有申请
            ResignCommit original = resignCommitService.getResignCommit(id);
            if (original == null) {
                return "not_found";
            }
            // 只允许删除未审批的申请
            if (original.getStatus() != 0) {
                return "approved";
            }
            return resignCommitService.deleteResignCommit(id) ? "success" : "failure";
        } catch (Exception e) {
            return "failure";
        }
    }

    /**
     * 批量删除辞职申请
     *
     * @param nums 辞职申请ID字符串，以逗号分隔
     * @return 返回操作结果字符串
     */
    @RequestMapping("/deleteResigns")
    @ResponseBody
    public String deleteResigns(@RequestParam("nums") String nums) {
        String[] ids = nums.split(",");
        boolean success = true;
        for (String id : ids) {
            if (!id.isEmpty()) {
                try {
                    ResignCommit original = resignCommitService.getResignCommit(Long.parseLong(id));
                    if (original != null && original.getStatus() == 0) {
                        success &= resignCommitService.deleteResignCommit(Long.parseLong(id));
                    }
                } catch (Exception e) {
                    success = false;
                }
            }
        }
        return success ? "success" : "failure";
    }

    /**
     * 审批辞职申请
     *
     * @param id 辞职申请ID
     * @param remark 审批备注（可选）
     * @return 返回操作结果字符串
     */
    @RequestMapping("/approveResign")
    @ResponseBody
    public String approveResign(@RequestParam("id") Long id, @RequestParam(required = false) String remark) {
        try {
            ResignCommit resignCommit = new ResignCommit();
            resignCommit.setId(id);
            resignCommit.setStatus(1); // 设置状态为通过
            resignCommit.setRemark(remark);
            boolean update = resignCommitService.updateResignCommit(resignCommit);
            if (update){
                // 退岗操作
                ResignCommit resignCommit1 = resignCommitService.getResignCommit(id);
                StudentJob studentJob = new StudentJob();
                studentJob.setJobPositionId(resignCommit1.getJobPositionId());
                studentJob.setUserId(resignCommit1.getUserId());
                studentJob.setStatus(-1);
                boolean b = studentJobService.updateJobStatus(studentJob);
                return  b? "success" : "failure";
            }
            return "failure";
        } catch (Exception e) {
            return "failure";
        }
    }

    /**
     * 拒绝辞职申请
     *
     * @param id 辞职申请ID
     * @param remark 拒绝备注
     * @return 返回操作结果字符串
     */
    @RequestMapping("/rejectResign")
    @ResponseBody
    public String rejectResign(@RequestParam("id") Long id, @RequestParam String remark) {
        try {
            ResignCommit resignCommit = new ResignCommit();
            resignCommit.setId(id);
            resignCommit.setStatus(-1); // 设置状态为拒绝
            resignCommit.setRemark(remark);
            return resignCommitService.updateResignCommit(resignCommit) ? "success" : "failure";
        } catch (Exception e) {
            return "failure";
        }
    }
}
